const http = require('http');
const net = require('net');
const url = require('url');
const { SocksClient } = require('socks');

// SOCKS5代理配置
const SOCKS_HOST = '113.45.152.80';
const SOCKS_PORT = 7878;
const SOCKS_USER = 'ynd777';
const SOCKS_PASS = 'ynd777';

const PROXY_HOST = '127.0.0.1';
const PROXY_PORT = 8888;

// 处理HTTP请求
function handleHttpRequest(req, res) {
  let targetUrl;
  if (req.url.startsWith('http://') || req.url.startsWith('https://')) {
    targetUrl = req.url;
  } else {
    const host = req.headers.host;
    if (!host) {
      res.writeHead(400, { 'Content-Type': 'text/plain' });
      res.end('缺少Host头');
      return;
    }
    targetUrl = `http://${host}${req.url}`;
  }
  const parsedUrl = url.parse(targetUrl);
  const destHost = parsedUrl.hostname;
  const destPort = parsedUrl.port ? parseInt(parsedUrl.port) : 80;

  // 通过SOCKS5代理建立到目标的socket
  SocksClient.createConnection({
    proxy: {
      host: SOCKS_HOST,
      port: SOCKS_PORT,
      type: 5,
      userId: SOCKS_USER,
      password: SOCKS_PASS
    },
    command: 'connect',
    destination: {
      host: destHost,
      port: destPort
    }
  }).then(info => {
    // 构建HTTP请求
    const requestLine = `${req.method} ${parsedUrl.path} HTTP/1.1\r\n`;
    const headers = Object.keys(req.headers)
      .map(key => `${key}: ${req.headers[key]}`)
      .join('\r\n');
    const httpRequest = requestLine + headers + '\r\n\r\n';
    info.socket.write(httpRequest);
    req.pipe(info.socket);
    // 处理响应
    info.socket.pipe(res);
    info.socket.on('error', err => {
      if (!res.headersSent) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('SOCKS代理连接错误: ' + err.message);
      }
    });
    res.on('close', () => info.socket.destroy());
  }).catch(err => {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('SOCKS代理连接失败: ' + err.message);
  });
}

// 处理HTTPS CONNECT请求
function handleConnectRequest(req, clientSocket, head) {
  const [host, port] = req.url.split(':');
  const destPort = port ? parseInt(port) : 443;
  // 通过SOCKS5代理建立到目标的socket
  SocksClient.createConnection({
    proxy: {
      host: SOCKS_HOST,
      port: SOCKS_PORT,
      type: 5,
      userId: SOCKS_USER,
      password: SOCKS_PASS
    },
    command: 'connect',
    destination: {
      host: host,
      port: destPort
    }
  }).then(info => {
    clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
    // 双向转发
    info.socket.write(head);
    clientSocket.pipe(info.socket);
    info.socket.pipe(clientSocket);
    info.socket.on('error', () => clientSocket.destroy());
    clientSocket.on('error', () => info.socket.destroy());
  }).catch(err => {
    clientSocket.write('HTTP/1.1 500 Connection Error\r\n\r\n');
    clientSocket.destroy();
  });
}

// 创建HTTP代理服务器
const server = http.createServer();
server.on('request', handleHttpRequest);
server.on('connect', handleConnectRequest);

server.listen(PROXY_PORT, PROXY_HOST, () => {
  console.log('HTTP代理服务器已启动');
  console.log(`监听地址: ${PROXY_HOST}:${PROXY_PORT}`);
  console.log(`SOCKS代理: ${SOCKS_HOST}:${SOCKS_PORT}`);
  console.log(`用户名: ${SOCKS_USER}`);
  console.log('所有HTTP/HTTPS请求都将通过SOCKS5代理转发!');
}); 